using Microsoft.AspNetCore.Mvc;
using community.Models;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using community.Data;

namespace community.Controllers
{
    /// <summary>
    /// 居委会查询参数
    /// </summary>
    public class CommitteeQueryDTO
    {
        /// <summary>
        /// 居委会名称
        /// </summary>
        public string? Name { get; set; }

        /// <summary>
        /// 每页显示数量，默认10条
        /// </summary>
        [Range(1, 100)]
        public int PageSize { get; set; } = 10;

        /// <summary>
        /// 当前页码，默认第1页
        /// </summary>
        [Range(1, int.MaxValue)]
        public int PageNumber { get; set; } = 1;
    }

    /// <summary>
    /// 创建/更新居委会的数据模型
    /// </summary>
    public class CommitteeDTO
    {
        /// <summary>
        /// 居委会名称
        /// </summary>
        [Required(ErrorMessage = "居委会名称不能为空")]
        [StringLength(100, ErrorMessage = "居委会名称最多100个字符")]
        public string Name { get; set; }

        /// <summary>
        /// 居委会描述
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// 居委会地址
        /// </summary>
        [Required(ErrorMessage = "居委会地址不能为空")]
        [StringLength(200, ErrorMessage = "居委会地址最多200个字符")]
        public string Address { get; set; }

        /// <summary>
        /// 联系电话
        /// </summary>
        [Required(ErrorMessage = "联系电话不能为空")]
        [Phone(ErrorMessage = "请输入有效的电话号码")]
        public string ContactPhone { get; set; }
    }

    /// <summary>
    /// 居委会管理接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class CommitteeController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public CommitteeController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取居委会列表（支持分页和条件筛选）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>居委会列表和总数</returns>
        /// <response code="200">成功获取居委会列表</response>
        /// <response code="400">查询参数验证失败</response>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> GetCommittees([FromQuery] CommitteeQueryDTO query)
        {
            var committees = _context.Committee.AsQueryable();

            if (!string.IsNullOrEmpty(query.Name))
                committees = committees.Where(c => c.Name.Contains(query.Name));

            var total = await committees.CountAsync();

            var pagedCommittees = await committees
                .Skip((query.PageNumber - 1) * query.PageSize)
                .Take(query.PageSize)
                .ToListAsync();

            return Ok(new
            {
                Total = total,
                Items = pagedCommittees
            });
        }

        /// <summary>
        /// 获取指定居委会的详细信息
        /// </summary>
        /// <param name="id">居委会ID</param>
        /// <returns>居委会详细信息</returns>
        /// <response code="200">成功获取居委会信息</response>
        /// <response code="404">指定ID的居委会不存在</response>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetCommittee(int id)
        {
            var committee = await _context.Committee
                .Include(c => c.Complexes)
                .FirstOrDefaultAsync(c => c.Id == id);

            if (committee == null)
                return NotFound();

            return Ok(committee);
        }

        /// <summary>
        /// 创建新居委会
        /// </summary>
        /// <param name="dto">居委会信息</param>
        /// <returns>新创建的居委会信息</returns>
        /// <response code="201">成功创建居委会</response>
        /// <response code="400">提供的数据无效</response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> CreateCommittee(CommitteeDTO dto)
        {
            var committee = new Committee
            {
                Name = dto.Name,
                Description = dto.Description,
                Address = dto.Address,
                ContactPhone = dto.ContactPhone,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            _context.Committee.Add(committee);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetCommittee), new { id = committee.Id }, committee);
        }

        /// <summary>
        /// 更新居委会信息
        /// </summary>
        /// <param name="id">居委会ID</param>
        /// <param name="dto">更新的居委会信息</param>
        /// <returns>更新后的居委会信息</returns>
        /// <response code="200">成功更新居委会信息</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的居委会不存在</response>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateCommittee(int id, CommitteeDTO dto)
        {
            var committee = await _context.Committee.FindAsync(id);
            if (committee == null)
                return NotFound();

            committee.Name = dto.Name;
            committee.Description = dto.Description;
            committee.Address = dto.Address;
            committee.ContactPhone = dto.ContactPhone;
            committee.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(committee);
        }

        /// <summary>
        /// 删除居委会
        /// </summary>
        /// <param name="id">居委会ID</param>
        /// <returns>无内容</returns>
        /// <response code="204">成功删除居委会</response>
        /// <response code="404">指定ID的居委会不存在</response>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteCommittee(int id)
        {
            var committee = await _context.Committee.FindAsync(id);
            if (committee == null)
                return NotFound();

            _context.Committee.Remove(committee);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        /// <summary>
        /// 获取居委会下属小区列表
        /// </summary>
        /// <param name="id">居委会ID</param>
        /// <returns>小区列表</returns>
        /// <response code="200">成功获取小区列表</response>
        /// <response code="404">居委会不存在</response>
        [HttpGet("{id}/complexes")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetCommitteeComplexes(int id)
        {
            var committee = await _context.Committee
                .Include(c => c.Complexes)
                .FirstOrDefaultAsync(c => c.Id == id);

            if (committee == null)
            {
                return NotFound(new { message = "居委会不存在" });
            }

            return Ok(committee.Complexes);
        }
    }
} 